package be.cgi.heroesmanager.providers;

import java.util.regex.Matcher;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import be.cgi.heroesmanager.db.HeroesAdapter;

public class HeroesProvider extends ContentProvider {
	private HeroesAdapter adap;

	private static final String authority = "be.cgi.heroesprovider";
	private final String CONTENT_URI = "content://" + authority;

	private static final int ALL_HEROES = 1000;
	private static final int ONE_HERO = 2000;

	private static UriMatcher matcher;
	static {
		matcher = new UriMatcher(UriMatcher.NO_MATCH);
		matcher.addURI(authority, "heroes", ALL_HEROES);
		matcher.addURI(authority, "heroes/#", ONE_HERO);
	}

	@Override
	public boolean onCreate() {
		adap = new HeroesAdapter(getContext());
		adap.openWritable();

		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {

		switch (matcher.match(uri)) {
		case ALL_HEROES:
			return adap.getAllCursor();
		case ONE_HERO:
			int id = Integer.parseInt(uri.getPathSegments().get(1));
			return adap.getOneCursor(id);
		}

		return null;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		long id = adap.insert(values);

		String completeUri = CONTENT_URI + "/heroes/" + id;

		return Uri.parse(completeUri);
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}
}
